from django.contrib.auth import login as auth_login, logout as auth_logout, authenticate
from django.shortcuts import render, redirect
from django.contrib import messages
from .models import User
from django.http import HttpResponse

# Create your views here.
def login(request):

    if request.method == 'GET':
        return render(request, 'users/login.html')

    # 获取登录的账号密码
    username = request.POST.get('username')
    password = request.POST.get('password')

    #验证输入是否为空
    if not username or not password:
        # 使用messages框架（推荐）或返回错误上下文
        messages.error(request, '用户名和密码不能为空')
        return render(request, 'users/login.html')

    # 4. 使用authenticate函数进行认证（核心修复）
    user = authenticate(request, username=username, password=password)

    # 5. 判断认证结果
    if user is not None:
        # 认证成功：使用Django内置的login函数建立会话
        auth_login(request, user)
        # 重定向到首页，而不是渲染
        return redirect('create:index')
    else:
        # 认证失败：返回错误信息
        messages.error(request, '用户名或密码错误')
        return render(request, 'users/login.html')

def logout(request):
    auth_logout(request)
    return redirect('user:login')

def register(request):

    if request.method == 'GET':
        return render(request,'users/register.html')

    # 获取注册的账号密码和二次密码
    username = request.POST.get('username')
    password = request.POST.get('password')
    confirm_password = request.POST.get('confirm_password')

    # 在数据库查找用户
    user= User.objects.filter(username=username).first()

    # 判断用户是否存在
    if user:
        messages.error(request, '用户已存在')
        return render(request, 'users/register.html')

    # 判断用户第二次输入的密码与第一次是否一致
    if password != confirm_password:
        messages.error(request, '密码输入错误')
        return render(request, 'users/register.html')

    # 条件全部满足之后创建账号到数据库并重定向到登录界面
    else:
        User.objects.create_user(username=username, password=password)
        messages.success(request, '账号创建成功')
        return redirect('user:login')




